package com.example.dzl.controller;

import com.example.dzl.request.LoginRequest;
import com.example.dzl.request.RefreshTokenRequest;
import com.example.dzl.response.TokenResponse;
import com.example.dzl.util.JwtTokenUtil;
import com.example.dzl.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/auth")
@Slf4j
public class AuthController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest loginRequest) {
        log.info("用户登录：{}", loginRequest);
        // 简化验证 - 实际项目中应使用UserDetailsService
        if ("admin".equals(loginRequest.getUsername()) && "123456".equals(loginRequest.getPassword())) {
            log.info("用户登录成功：{}", loginRequest.getUsername());
            String accessToken = jwtTokenUtil.generateAccessToken(loginRequest.getUsername());
            String refreshToken = jwtTokenUtil.generateRefreshToken(loginRequest.getUsername());

            TokenResponse tokenResponse = new TokenResponse(accessToken, refreshToken, 3600L);

            log.info("用户登录成功：{}", tokenResponse);
            return Result.success(tokenResponse);
        } else {
            return Result.error(HttpStatus.UNAUTHORIZED.value(), "用户名或密码错误");
        }
    }

    @PostMapping("/refresh")
    public Result refreshToken(@RequestBody RefreshTokenRequest request) {
        log.info("用户刷新Token：{}", request);

        String refreshToken = request.getRefreshToken();

        if (jwtTokenUtil.validateToken(refreshToken) && !jwtTokenUtil.isTokenExpired(refreshToken)) {
            log.info("用户刷新Token成功！");
            String username = jwtTokenUtil.getUsernameFromToken(refreshToken);
            String newAccessToken = jwtTokenUtil.generateAccessToken(username);
            String newRefreshToken = jwtTokenUtil.generateRefreshToken(username);

            TokenResponse tokenResponse = new TokenResponse(newAccessToken, newRefreshToken, 3600L);
            log.info("用户刷新Token成功：{}", tokenResponse);
            return Result.success(tokenResponse);
        } else {
            
            return Result.error(HttpStatus.UNAUTHORIZED.value(), "Refresh Token无效或已过期");
        }
    }
}